package com.jht.mymvvm.activity.homepage

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.jht.mymvvm.R
import kotlinx.android.synthetic.main.activity_homepage.*
import kotlinx.android.synthetic.main.activity_homepage.view.*


private const val TAG = "HomepageActivity"
class HomepageActivity : AppCompatActivity() {
    lateinit var viewModel: HomepageViewModel
    lateinit var preferences: SharedPreferences
    lateinit var userViewModel: UserInfoViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_homepage)
        preferences = getPreferences(Context.MODE_PRIVATE)
        val countReserved = preferences.getInt("count_reserved",0)
        viewModel = ViewModelProvider(this,HomepageViewModelFactory(countReserved)).get(HomepageViewModel::class.java)

        userViewModel = ViewModelProvider(this).get(UserInfoViewModel::class.java)
        btn_add.setOnClickListener{
            viewModel.count++
            refreshCounter()
        }
        btn_clear.setOnClickListener{
            viewModel.count = 0
            refreshCounter()
        }
        refreshCounter()

        userViewModel.user.observe(this){
            it.forEach{
                Log.e(TAG, "onCreate: ${it.firstName} and ${it.id}")
            }
        }

        change_name.setOnClickListener{
            //ed_1
            Log.e(TAG, "onCreate: ${ed_1.text.toString()}")
            userViewModel.setName(ed_1.text.toString())
        }



    }

    private fun refreshCounter(){
        textView.text =  viewModel.count.toString()
    }

    override fun onPause() {
        super.onPause()
        val putInt = preferences.edit()
        putInt.putInt("count_reserved", viewModel.count)
        putInt.apply()
    }

}